﻿using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;

namespace FDStudio.Core.Runtime
{
    /*
     CreatedOn: 2018-01-25
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 程序集加载
    /// </summary>
    public class AssemblyLoader : AssemblyLoadContext
    {
        protected override Assembly Load(AssemblyName assemblyName)
        {
            var deps = DependencyContext.Default;
            //Log(deps);
            var version = assemblyName.Version.ToString().Replace("{", "").Replace("}", "");
            var index = version.LastIndexOf('.');
            version = version.Substring(0, index);
            var res = deps.CompileLibraries.Where(d => d.Name.Contains(assemblyName.Name) && d.Version == version);
            var assembly = Assembly.Load(res.Count() > 0 ? new AssemblyName(res.First().Name) : assemblyName);
            return assembly;
        }

        public void Log(DependencyContext dex)
        {
            Log("CompileLibraries:");
            dex.CompileLibraries.ToList().ForEach(d =>
            {
                Log(d.Name);
            });
            Log("==================================\r\nRuntimeLibraries:");
            dex.RuntimeLibraries.ToList().ForEach(d =>
            {
                Log(d.Name);
            });
        }

        private void Log(string msg)
        {
            System.IO.File.AppendAllText(@"D:\lib.log", $"{msg}\r\n");
        }
    }
}
